/**
 * Created by 小敏哥 on 2017/8/21.
 * 上传组件
 */
import React, {Component} from 'react';
import lrz from 'lrz';
import {Toast} from 'antd-mobile';
import style from './index.scss';
import ReModal from '../../common/reModal';
import jsApi from '../../../utils/cx580.jsApi';
import typeOfBrowser from '../../../utils/typeOfBrowser';
import AlipayJSOperation from '../../../utils/alipayJSOperation';

class UploadImg extends Component {
    constructor(props) {
        super(props);
        this.imgFileChange = this.imgFileChange.bind(this);
        this.state = {
            imgCache: ''
        }
    }

    static propTypes = {
        width:React.PropTypes.string.isRequired,//宽度
        height:React.PropTypes.string.isRequired,//高度
        fileChange: React.PropTypes.func,//选择图片改变后回调
        uploaded: React.PropTypes.bool,//图片上传状态，false：未上传，true：已上传
        backgroundImage:React.PropTypes.string,//背景图片

        //以下为组件各种操作的钩子函数，方便跟踪组件的操作
        uploadClickCallBack:React.PropTypes.func,//点击上传资料回调
        deleteClickCallBack:React.PropTypes.func,//点击删除按钮回调
        deleteOkCallBack:React.PropTypes.func,//确认删除回调
        deleteCancelCallBack:React.PropTypes.func,//取消删除回调
    };


    /**
     * 图片压缩上传
     * @param e 图片资源
     */
    compressImage(files, callBack) {
        try {
            Toast.hide();
            Toast.loading("正在上传", 30);
            let quality = 1;
            if (files.size > 1024 * 100) {
                quality = .5;
            } else {
                quality = .7;
            }
            lrz(files, {
                width: 1024,
                quality: quality
            }).then((rst) => {
                Toast.hide();
                callBack(rst.base64);
            }).catch((err) => {
                Toast.fail('上传失败', 2);
            }).always(() => {
            });
        } catch (e) {
            Toast.fail('上传失败', 2);
            console.log(e);
        }

    };

    //改变显示的图片
    changeImgAndCallBack(result){
        this.setState({
            imgCache: result
        });
        this.props.fileChange && this.props.fileChange(result);
    }

    //图片改变时触发上传操作
    imgFileChange(e) {
        this.compressImage(e.target.files[0], (result) => {
            this.changeImgAndCallBack(result);
        });
    }

    //APP图片上传，旧版本app有一部分手机用input选择文件失败，故app统一使用sdk进行调用
    appUploadImg(callback) {
        //默认
        let data = {
            "quality": 75,/*图片质量, 取值1到100*/
            "maxWidth": 768,/*图片的最大宽度. 过大将被等比缩小*/
            "maxHeight": 768,/*图片的最大高度. 过大将被等比缩小*/
            "maxSize": 500
        };
      /*  let version = common.getAppVersion();

        if (version) {
            version = version.split(".");
            if ((version[0] * 1) > 6 || ((version[0] * 1) > 5 && (version[1] * 1) > 0)) {
                //APP 6.1.0以上
            } else {
                //APP 6.1.0以下
                data = {
                    "quality": 75,/!*图片质量, 取值1到100*!/
                    "maxWidth": 512,/!*图片的最大宽度. 过大将被等比缩小*!/
                    "maxHeight": 512,/!*图片的最大高度. 过大将被等比缩小*!/
                    "maxSize": 300
                };
            }
        }*/
        try {
            jsApi.call({
                "commandId": "",/*命令主键，每次调用，必须用全局唯一的字符串*/
                "command": "picture",/*执行的命令，原生APP会根据此值执行相应的逻辑*/
                "data": data
            }, function (result) {
                callback(result.data.dataBase64); //回调函数
            });
        } catch (error) {
            Toast.fail('上传失败',2);
        }

    }


    //点击触发上传
    contentClick() {
        if( this.props.uploaded){
            return;
        }
        if(typeOfBrowser.getChannelOfBrowser()=='app'){
            this.appUploadImg((result)=>{
                this.changeImgAndCallBack(result);
            })
        }
        else if(typeOfBrowser.getChannelOfBrowser()=='aliPay'){
            AlipayJSOperation.uploadPhoto((result)=>{
                this.changeImgAndCallBack(result);
            })
        }
        else {
            this.refs.uploadCompent.click();
        }
        this.props.uploadClickCallBack&&this.props.uploadClickCallBack();
    }

    getBackgroundStyle() {
        return !this.props.uploaded||!this.state.imgCache ? {width: this.props.width, height: this.props.height,backgroundImage:`url(${this.props.backgroundImage})`,backgroundSize:'100% 100%'} : {width: this.props.width, height: this.props.height};
    }

    //删除已上传的图片
    deleteImg(){
        this.state.imgCache&&ReModal.confirm('确定删除已上传图片？',()=>{
            this.setState({
                imgCache:''
            });
            this.refs.uploadCompent.value='';
            //删除图片后触发文件改变回调
            this.props.fileChange && this.props.fileChange('');
            this.props.deleteOkCallBack&&this.props.deleteOkCallBack();
        },()=>{
            this.props.deleteCancelCallBack&&this.props.deleteCancelCallBack();
        });
        this.props.deleteClickCallBack&&this.props.deleteClickCallBack();
    }


    render() {
        return <div className={style.container} style={{width: this.props.width, height: this.props.height}}>
            <div className={style.imgContainer} style={this.getBackgroundStyle()} onClick={() => {
                this.contentClick()
            }}>
                <img src={this.props.uploaded?this.state.imgCache:''}/>
            </div>
            {this.state.imgCache&&this.props.uploaded ? <div className={style.deleteIcon} onClick={this.deleteImg.bind(this)}><div></div></div> : ''}
            <input ref="uploadCompent" type="file" accept="image/*" onChange={(e) => this.imgFileChange(e)}
                   className={style.uploadCompent}/>
        </div>
    }
}

export default UploadImg;